<template>
  <section class="app-container">
    <div class="content">
      <div class="content-head">
        <el-row>
          <el-col :span="24">
            <el-form :inline="true" :model="queryData" class="demo-form-inline">
              <el-form-item label="选择部门">
                <el-cascader
                  v-model="queryData.orgId"
                  :options="departmentList"
                  :props="{ expandTrigger: 'hover',value: 'orgId',label: 'orgName',checkStrictly: true }"
                  placeholder="请选择"
                />
              </el-form-item>
              <el-form-item label="选择角色">
                <el-select v-model="queryData.roleId" filterable class="width-150" placeholder="选择角色">
                  <el-option v-for="item in roleList" :key="item.roleId" :label="item.roleName" :value="item.roleId" />
                </el-select>
              </el-form-item>
              <el-form-item label="关键字">
                <el-input v-model.trim="queryData.keyword" class="width-150" placeholder="姓名/工号/手机/邮箱" clearable @keyup.enter.native="getTableList(true)" />
              </el-form-item>
              <el-form-item>
                <el-button type="primary" size="small" icon="el-icon-search" @click="getTableList(true)">查询</el-button>
                <el-button type="primary" size="small" icon="el-icon-refresh-left" @click="reset()">重置</el-button>
              </el-form-item>
            </el-form>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="16">
            <el-button v-p="'userManageAdd'" type="primary" size="small" icon="el-icon-plus" @click="openDialog('add')">新增用户</el-button>
            <el-button v-p="'userManageUpdateDep'" size="small" @click="batchOperate('updateDepartment')">修改部门</el-button>
            <el-button v-p="'userManageUpdateUser'" size="small" @click="batchOperate('updateRole')">修改角色</el-button>
            <el-button v-p="'userManageStopUser'" size="small" @click="batchOperate('stopUse')">停用员工</el-button>
          </el-col>
          <el-col :span="8" class="text-right">
            <div>
              <el-link icon="fa fa-question-circle-o" @click="help">帮助说明</el-link>
              <!-- <el-button size="small" @click="Utils.building">手动排序</el-button>
              <el-button size="small" @click="Utils.building">按字母排序</el-button> -->
            </div>
          </el-col>
        </el-row>
      </div>
      <!--列表 -->
      <el-table v-loading="tableListLoading" :data="tableList" highlight-current-row height="600" size="small" stripe border @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="40" fixed />
        <el-table-column type="index" label="序号" width="50" fixed />
        <el-table-column prop="chName" label="姓名" min-width="100" sortable />
        <el-table-column prop="username" label="工号" min-width="100" sortable />
        <el-table-column prop="gender" label="性别" min-width="70" sortable>
          <template slot-scope="scope">
            <span>{{ scope.row.gender | formatGender }}</span>
          </template>
        </el-table-column>

        <el-table-column prop="mobile" label="手机" min-width="100" sortable />
        <el-table-column prop="email" label="邮箱" min-width="140" sortable />
        <el-table-column prop="orgName" label="部门" min-width="100" sortable />
        <el-table-column prop="roleName" label="角色" min-width="100" sortable />
        <el-table-column prop="remark" label="备注" min-width="100" sortable show-overflow-tooltip />
        <el-table-column prop="roleName" label="角色" min-width="100" sortable />
        <el-table-column prop="status" label="状态" min-width="80" sortable>
          <template slot-scope="scope">
            <el-switch v-model="scope.row.status" disabled active-color="#13ce66" inactive-color="#ff4949" :active-value="1" :inactive-value="0" />
          </template>
        </el-table-column>
        <el-table-column prop="lastLoginTime" label="最后登录" min-width="140" sortable>
          <template slot-scope="scope">
            <span>{{ scope.row.lastLoginTime | formatDateToStr }}</span>
          </template>
        </el-table-column>

        <el-table-column label="操作" min-width="140" fixed="right">
          <template slot-scope="scope">
            <a v-p="'userManageUpdate'" href="javascript:;" class="text-blue inline-block" @click="openDialog('edit',scope.row)"><i class="el-icon-edit" />编辑</a>
            <a v-p="'userManageIsUse'" href="javascript:;" class="text-blue inline-block" @click="switchStaus(scope.row)"><i class="el-icon-remove" />{{ scope.row.status===1?'停用':'启用' }}</a>
            <a v-p="'userManageDelete'" href="javascript:;" class="text-danger inline-block" @click="deleteItem(scope.row)"><i class="el-icon-delete" />删除</a>

          </template>
        </el-table-column>
      </el-table>
      <div class="element-page clearfix">
        <el-pagination
          :current-page="currentPage"
          :page-sizes="[10, 20, 50, 100, 500]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
        <el-button type="primary" class="pag-go">GO</el-button>
      </div>
    </div>
    <div>
      <!--新增/修改-弹窗  -->
      <el-dialog :title="dialogType=='add'?'新增用户':'修改用户'" width="40%" :visible.sync="dialogVisible" :close-on-click-modal="false" @opened="listenOpenedDialog" @closed="listenClosedDialog">
        <el-form ref="dialogFormData" :model="dialogFormData" label-width="160px" :rules="dialogFormDataRules">
          <el-form-item label="所属部门:" prop="orgId">
            <el-cascader
              v-model="dialogFormData.orgId"
              :options="departmentList"
              :props="{ expandTrigger: 'hover',value: 'orgId',label: 'orgName',checkStrictly: true }"
              placeholder="请选择"
            />
          </el-form-item>
          <el-form-item label="当前角色:" prop="roleId">
            <el-select v-model="dialogFormData.roleId" class="width-150" placeholder="选择角色">
              <el-option v-for="item in roleList" :key="item.roleId" :label="item.roleName" :value="item.roleId" />
            </el-select>
          </el-form-item>
          <el-form-item label="用户姓名:" prop="chName">
            <el-input v-model.trim="dialogFormData.chName" placeholder="请输入用户姓名" clearable maxlength="50" />
          </el-form-item>
          <el-form-item label="工号:" prop="username">
            <el-input v-model.trim="dialogFormData.username" placeholder="请输入工号" clearable maxlength="50" />
          </el-form-item>
          <el-form-item label="登录密码:" prop="password">
            <el-input v-model.trim="dialogFormData.password" placeholder="请输入登录密码" clearable maxlength="50" />
          </el-form-item>

          <el-form-item label="员工性别:" prop="gender">
            <el-radio v-model="dialogFormData.gender" :label="1">男</el-radio>
            <el-radio v-model="dialogFormData.gender" :label="2">女</el-radio>
            <el-radio v-model="dialogFormData.gender" :label="0">保密</el-radio>
          </el-form-item>
          <el-form-item label="邮箱地址:" prop="email">
            <el-input v-model.trim="dialogFormData.email" placeholder="请输入邮箱地址" clearable maxlength="50" />
          </el-form-item>
          <el-form-item label="手机号码:" prop="mobile">
            <el-input v-model.trim="dialogFormData.mobile" placeholder="请输入手机号码" clearable maxlength="50" />
          </el-form-item>
          <el-form-item label="启用状态:" prop="status">
            <el-select v-model="dialogFormData.status">
              <el-option :value="1" label="启用" />
              <el-option :value="0" label="关闭" />
            </el-select>
          </el-form-item>
          <el-form-item label="备注:" prop="remark">
            <el-input v-model.trim="dialogFormData.remark" type="textarea" placeholder="在此输入备注信息" maxlength="300" />
          </el-form-item>

        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click.native="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="dialogFormDataSubmit('dialogFormData')">立即提交</el-button>
        </div>
      </el-dialog>
      <!-- 修改部门 -->
      <update-department :dialog-prop="updateDepartmentVisible" :user-list="userList" @getTableList="getTableList" />
      <!-- 修改角色 -->
      <update-Role :dialog-prop="updateRoleVisible" :user-list="userList" @getTableList="getTableList" />
      <!-- 停用 -->
      <stop-use :dialog-prop="stopUseVisible" :user-list="userList" @getTableList="getTableList" />
    </div>

  </section>

</template>

<script>
import { validMobile, validEmail, validPassword } from '@/utils/validate'
import { queryUserByPage, addUser, updateUser, isUseUser, deleteUser } from '@/api/api'
import md5 from 'js-md5'

export default {
  components: {
    'UpdateDepartment': () => import(`./UserUpdateDepartment.vue`),
    'UpdateRole': () => import(`./UserUpdateRole.vue`),
    'StopUse': () => import(`./UserStopUse.vue`)
  },
  data() {
    return {

      currentPage: 1, // 当前页
      total: 0, // 总页数
      pageSize: 20, // 页码
      tableListLoading: false, // 加载loading
      // 查询表单数据
      queryData: {
        orgId: '',
        roleId: '',
        keyword: ''
      },
      // 部门数据
      departmentList: null,
      // 角色数据
      roleList: null,
      // 表格数据
      tableList: [],
      // 新增/修改弹窗相关数据
      dialogVisible: false,
      dialogType: 'add',
      // 表单数据
      dialogFormData: {
        chName: '',
        username: '',
        password: '',
        orgId: '',
        roleId: '',
        gender: 1,
        email: '',
        mobile: '',
        status: 1,
        remark: ''
      },
      // 表单数据验证
      dialogFormDataRules: {
        chName: [
          { required: true, message: '请输入用户姓名', trigger: 'blur' }
        ],
        username: [
          { required: true, message: '请输入工号', trigger: 'blur' }
        ],
        password: [
          { required: true, validator: validPassword, trigger: 'blur' }
        ],
        orgId: [
          { required: true, message: '请输入所属部门', trigger: 'blur' }
        ],
        roleId: [
          { required: true, message: '请输入当前角色', trigger: 'blur' }
        ],
        gender: [
          { required: true, message: '请输入员工性别', trigger: 'blur' }
        ],
        email: [
          { required: true, validator: validEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, validator: validMobile, trigger: 'blur' }
        ]

      },
      updateDepartmentVisible: {
        visible: false
      },
      updateRoleVisible: {
        visible: false
      },
      stopUseVisible: {
        visible: false
      },
      userList: []
    }
  },
  mounted() {
    this.getTableList(false)
    setTimeout(() => {
      const tempList = this.Utils.deepCopy(this.$store.getters.departmentList)
      this.departmentList = this.Utils.isHasChildren(tempList)

      this.roleList = this.$store.getters.roleList
    }, 800)
  },

  methods: {
    /**
     * 查询
     * @param {(Boolean)} isFirst  是否从第1页开始查询
     */
    getTableList(isFirst) {
      const params = {
        pageNum: this.currentPage,
        pageSize: this.pageSize
      }
      if (isFirst) {
        params.pageNum = 1
      }

      Object.assign(params, this.queryData)
      if (params.orgId && params.orgId.length) {
        params.orgId = this.queryData.orgId[this.queryData.orgId.length - 1]
      }
      this.tableListLoading = true
      queryUserByPage(params).then(res => {
        this.tableListLoading = false

        if (res.code === '0000') {
          this.total = res.data.total
          this.tableList = res.data.list
        }
      // eslint-disable-next-line handle-callback-err
      }).catch(error => {
        this.tableListLoading = false
      })
    },
    /**
     * 打开新增/编辑弹窗
     * @param {(String)} type  弹窗类型,"add=新增,edit=修改"
     * @param {(Object)} row  操作行数据,修改时传
     */
    openDialog(type, row) {
      this.dialogType = type
      this.dialogVisible = true
      if (type === 'edit') {
        this.dialogFormData = this.Utils.deepCopy(row)
        if (row.orgId === 0) {
          this.dialogFormData.orgId = [row.orgId]
        } else {
          this.dialogFormData.orgId = this.Utils.getParentIdList(row.orgId, this.departmentList)
          this.dialogFormData.orgId.push(row.orgId)
        }
      }
    },
    listenOpenedDialog() {

    },
    listenClosedDialog() {
      // 初始化表单状态
      this.$refs['dialogFormData'].resetFields()
      this.Utils.emptyObject(this.dialogFormData)
      this.dialogFormData.gender = 1
      this.dialogFormData.status = 1
    },

    // 新增编辑弹窗表单提交
    dialogFormDataSubmit(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          const params = this.Utils.deepCopy(this.dialogFormData)
          // console.log(this.dialogFormData.orgId)

          if (this.dialogFormData.orgId && this.dialogFormData.orgId.length) {
            params.orgId = this.dialogFormData.orgId[this.dialogFormData.orgId.length - 1]
          }

          if (this.dialogType === 'add') {
            params.password = md5(params.password)
            addUser(params).then(res => {
              if (res.code === '0000') {
                this.$message({
                  message: res.msg,
                  type: 'success'
                })
                this.dialogVisible = false
                this.getTableList(true)
              }
            })
          } else {
            // 如果是6个"**,标识不修改,原样返回
            if (this.dialogFormData.password !== '******') {
              params.password = md5(params.password)
            }
            updateUser(params).then(res => {
              if (res.code === '0000') {
                this.$message({
                  message: res.msg,
                  type: 'success'
                })
                this.dialogVisible = false
                this.getTableList(false)
              }
            })
          }
        } else {
          return false
        }
      })
    },
    reset() {
      this.queryData = this.Utils.emptyObject(this.queryData)
    },
    switchStaus(row) {
      const params = {
        userId: row.userId,
        status: Number(!row.status)
      }
      const operatType = row.status === 1 ? '停用' : '启用'
      this.$confirm(`您确定要${operatType}用户"${row.chName}"吗?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        isUseUser(params).then(res => {
          if (res.code === '0000') {
            this.$message({
              message: res.msg,
              type: 'success'
            })
            this.getTableList(false)
          }
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消'
        })
      })
    },
    deleteItem(row) {
      this.$confirm(`您确定要删除用户"${row.chName}"吗?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteUser({ userId: row.userId }).then(res => {
          if (res.code === '0000') {
            this.$message({
              message: res.msg,
              type: 'success'
            })
            this.getTableList(false)
          }
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消'
        })
      })
    },
    help() {
      this.$alert(`
        1、用户(员工),新增时选择部门和角色,登录请用工号登录；</br>
        2、为避免误操作,所有不提供批量重置密码,禁用,删除等操作；</br>
        3、权限赋予角色,角色分配给用户,从而达到系统整体的权限控制；</br>
      `, '帮助说明', {
        confirmButtonText: '确定',
        dangerouslyUseHTMLString: true
      })
    },
    batchOperate(type) {
      if (this.userList && this.userList.length) {
        if (type === 'updateDepartment') {
          this.updateDepartmentVisible.visible = true
        } else if (type === 'updateRole') {
          this.updateRoleVisible.visible = true
        } else if (type === 'stopUse') {
          this.stopUseVisible.visible = true
        }
      } else {
        this.$message({
          message: '请在表格左侧勾选要操作的用户',
          type: 'warning'
        })
      }
    },
    handleSelectionChange(val) {
      this.userList = val
    },
    // 每页数据大小
    handleSizeChange(val) {
      this.pageSize = val
      this.getListUser(false)
    },
    // 当前页
    handleCurrentChange(val) {
      this.currentPage = val
      this.getListUser(false)
    }

  }
}
</script>
<style lang="scss" scoped>

</style>
